const Router = require('koa-router')
const router = new Router();
const jwt = require("jsonwebtoken")
const { returnMsg, queryFn } = require("../../config")
// 导入 bcryptjs 这个包
const bcrypt = require('bcryptjs')

const regPassword = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,18}$/ //密码邮箱正则
const regUsername = /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{4,16}$/ // 账户正则

router.post("/", async ctx => {
    let { username, password } = ctx.request.body
    if (username, password) {
        if(!(password =='123456' && username=='admin')){
            if ( !regPassword.test(password)  && (!regUsername.test(username) || username === 'admin')){
                ctx.body = returnMsg(2, "登录失败", '参数格式错误')
                return
            }
        }
       
        // 查询数据库
        let sql = `select * from user where username = "${username}"`
        let result = await queryFn(sql)
        ctx.body = returnMsg(1, "查询结果", result)
        if (result.length > 0) {
            let token = jwt.sign(
                { username, password },
                "hanyu",
                { expiresIn: '1h' }
            )
            let sql1 = `update user set token = '${token}' where username = '${username}'`
            // 插入token
            let result1 = await queryFn(sql1)
            // 再次查询用户
            let result2 = await queryFn(sql)
            const compareResult = bcrypt.compareSync(password, result2[0].password)
            // if (!compareResult) return res.cc('登录失败！')
            if(compareResult){
                let obj = {
                    username : result2[0].username,
                    "cms-token" : result2[0].token,
                    avatar : result2[0].avatar,
                    player:result2[0].player,
                    editable:result2[0].editable,
                }
                ctx.response.body = returnMsg(0, "登录成功", obj)
            }else{
                ctx.response.body = returnMsg(2, "登录失败,密码错误！", )
            }
            
        } else {
            ctx.body = returnMsg(2, "用户不存在", '请先注册')
        }
    } else {
        ctx.body = returnMsg(2, "参数错误", '用户名或密码出错')
    }


})

module.exports = router